package com.scpii.api.controller.content;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.scpii.api.common.annoation.Pagination;
import com.scpii.api.common.base.BaseController;
import com.scpii.api.domain.content.Resources;
import com.scpii.api.service.content.ResourcesService;
import com.scpii.api.util.FileUtil;

@Controller
@RequestMapping("/content/resources")
public class ResourcesController extends BaseController {

	@Resource
	private ResourcesService resourcesService;

	@PreAuthorize("hasRole('ROLE_CLIENT')")
	@RequestMapping(value = "/target/{targetId}", method = RequestMethod.GET)
	@ResponseBody
	@Pagination
	public List<Resources> getResourcesByTargetId(
			@PathVariable("targetId") Long targetId, Resources record) {
		record.setTargetId(targetId);
		record.setSortBy("CREATE_DT");
		record.setSortOrder("desc");
		return resourcesService.selectBySelective(record);
	}

	@PreAuthorize("hasRole('ROLE_USER')")
	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public Boolean addResource(@RequestParam("targetId") Long targetId,
			@RequestParam("title") String title,
			@RequestParam("files") MultipartFile[] files) {
		List<Resources> resources = FileUtil.save(files, title, targetId);
		if (resources != null && resources.size() > 0) {
			resourcesService.insertSelective(resources);
			return true;
		} else {
			return false;
		}
	}
}
